package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.CommonAdapter;
import com.ycsj.goldmedalnewconcept.adapter.ViewHolder;
import com.ycsj.goldmedalnewconcept.bean.StudentHomeInfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;

// 作业推送详情列表
@SuppressLint({ "ResourceAsColor", "NewApi" })
public class HomeWorkDetailActivity extends Activity implements OnClickListener {

	private LinearLayout llBack;
	private LinearLayout llLoading;
	private LinearLayout llEmpty;
	private GridView gv;
	private String role;
	private String account;
	private String id;

	private Intent intent;
	private String userclass;

	private String time;
	private String rowid;
	private String date;
	private TextView tv_title;
	
	// 数据集合
	List<StudentHomeInfo.ListBean> oldDatas;

	// 适配器对象
	HomeWorkInfoAdapter mgvAdapter;
	

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_homeworkdetail);

		// 设置状态栏
		setBar();

		// 获取传递过来的数据
		initIntent();

		// 初始化控件
		initView();

		// 设置监听
		setOnListener();

		// 设置GridView
		initGv();

		// 请求数据
		http();
	}

	private void initGv() {
		oldDatas = new ArrayList<>();
		mgvAdapter = new HomeWorkInfoAdapter(this, oldDatas,
				R.layout.item_student_work);
		gv.setAdapter(mgvAdapter);
	}

	/**
	 * 初始化
	 */
	private void initIntent() {
		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");
		intent = getIntent();
		userclass = intent.getStringExtra("userclass");
		rowid = intent.getStringExtra("rowid");
		date = intent.getStringExtra("date");
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		gv = (GridView) findViewById(R.id.gv);
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_title.setText(date);
	}

	/**
	 * 请求接口数据
	 */
	private void http() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("userclass", userclass);
		builder.add("status", "0");
		builder.add("rowid", rowid);
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();

		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 请求失败,主线程更新UI操作
						if (llLoading != null) {
							llLoading.setVisibility(View.GONE);
						}
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息
				Gson gson = new Gson();
				String json = arg0.body().string();
				try {
					StudentHomeInfo info = GsonUtil.jsonToBean(json,
							StudentHomeInfo.class);
					final List<StudentHomeInfo.ListBean> newDatas = info
							.getList();

					
					// 对NewDatas进行排序,没有选中的数据配置最后
					final List<StudentHomeInfo.ListBean> selectDatas = new ArrayList<>();
					final List<StudentHomeInfo.ListBean> unselectDatas = new ArrayList<>();
					for (int i = 0; i < newDatas.size(); i++) {
						if ("1".equals(newDatas.get(i).getSelectedState())) {
							selectDatas.add(newDatas.get(i));
						} else {
							unselectDatas.add(newDatas.get(i));
						}
					}

					
					
					
					
					
					// 更新UI的操作
					runOnUiThread(new Runnable() {
						public void run() {
							if (null == newDatas || newDatas.size() == 0) {
								// 证明没有数据
								if (llLoading != null) {
									llLoading.setVisibility(View.GONE);
								}
								if (llEmpty != null) {
									llEmpty.setVisibility(View.VISIBLE);
								}
							} else {
								// 证明有数据
								if (llLoading != null) {
									llLoading.setVisibility(View.GONE);
								}
								if (llEmpty != null) {
									llEmpty.setVisibility(View.GONE);
								}
								oldDatas.clear();
//								oldDatas.addAll(newDatas);
								if (selectDatas.size() != 0) {
									oldDatas.addAll(selectDatas);
								}
								if (unselectDatas.size() != 0) {
									oldDatas.addAll(unselectDatas);
								}
								
								
								mgvAdapter.notifyDataSetChanged();
							}
						}
					});
				} catch (Exception e) {
					Log.i("test", "数据异常");
				}
			}
		});
	}

	/**
	 * 设置监听
	 */
	private void setOnListener() {
		llBack.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_back:
			// 返回
			finish();
			break;
		}
	}

	/**
	 * 适配器
	 * 
	 * @author Administrator
	 *
	 */
	class HomeWorkInfoAdapter extends CommonAdapter<StudentHomeInfo.ListBean> {

		public HomeWorkInfoAdapter(Context context,
				List<StudentHomeInfo.ListBean> datas, int layoutId) {
			super(context, datas, layoutId);
		}

		@Override
		public void convert(ViewHolder holder, StudentHomeInfo.ListBean info) {
			// 头像
			RoundImageView lvHead = holder.getView(R.id.lv_head);
			Picasso.with(HomeWorkDetailActivity.this).load(info.getIcon())
					.placeholder(R.drawable.header).into(lvHead);

			// 名称
			TextView tvName = holder.getView(R.id.tv_name);
			tvName.setText(info.getName());

			// 状态按钮
			ImageView lvState = holder.getView(R.id.lv_delete);
			if ("1".equals(info.getSelectedState())) {
				// 选中
				lvState.setImageResource(R.drawable.st_select);
			} else {
				lvState.setImageResource(R.drawable.st_normal);
			}
		}
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	@SuppressLint("InlinedApi")
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

}
